import { defineComponent, shallowReactive, useTemplateRef, shallowRef, watchEffect, ref } from 'vue'
import type { Rule, FormInstance } from 'ant-design-vue/es/form'
import { useUserStore } from '@/stores/user'
import {
  saveTemplateApi,
  deleteTemplateApi,
  queryTemplateListApi,
} from '@/api/ai-agent/detail/template'
import { message } from 'ant-design-vue'

export default defineComponent({
  name: 'templateComponent',
  props: {
    prompt: {
      type: Object,
      required: true,
    },
    variableList: {
      type: Array,
      required: true,
    },
  },
  setup(props) {
    const user = useUserStore()
    const saveTemplateVisible = shallowRef(false)
    const selectTemplateVisible = shallowRef(false)
    const listLoading = shallowRef(false)
    const formRef = useTemplateRef<FormInstance>('form-ref')
    const templateList = ref([])

    const saveModel = shallowReactive({
      templateName: '',
    })

    const selectModel = shallowReactive({
      templateName: '',
    })

    const rules: Record<string, Rule[]> = {
      templateName: [{ required: true, message: '模板名称不得为空', trigger: 'blur' }],
    }

    const changeSavePopover = () => {
      saveTemplateVisible.value = !saveTemplateVisible.value
    }

    const changeSelectPopover = () => {
      selectTemplateVisible.value = !selectTemplateVisible.value
    }

    const closeSavePopover = () => {
      saveTemplateVisible.value = false
    }

    const confirmSavePopover = () => {
      formRef.value.validate().then(saveTemplate)
    }

    const saveTemplate = async (form: typeof saveModel) => {
      const params = {
        ...form,
        ...props.prompt,
        companyId: user.companyId,
        profildId: user.profileId,
        profileName: user.profileName,
        variableList: props.variableList,
      }
      const res = await saveTemplateApi(params)
      console.log('保存模板', res)
    }

    const deleteTemplate = (id: string) => {
      return async () => {
        const params = {
          templateId: id,
          companyId: user.companyId,
        }
        const { code, msg } = await deleteTemplateApi(params)
        if (!code) {
          message.success(msg || '删除模板成功')
          await queryTemplateList()
        }
      }
    }

    const queryTemplateList = async () => {
      listLoading.value = true
      try {
        const params = {
          companyId: user.companyId,
          ...selectModel,
        }
        const { data } = await queryTemplateListApi(params)
        templateList.value = data
      } catch (error) {
        console.error('获取模板列表失败', error)
      } finally {
        listLoading.value = false
      }
    }

    watchEffect(() => {
      if (selectTemplateVisible.value) {
        queryTemplateList()
      }
    })

    return () => (
      <>
        <a-space class="mb-100px" size={12}>
          <a-popover
            v-model:open={saveTemplateVisible.value}
            title="保存指令模板"
            trigger="click"
            v-slots={{
              content: () => (
                <>
                  <a-form ref="form-ref" model={saveModel} rules={rules}>
                    <a-form-item name="templateName">
                      <a-input v-model:value={saveModel.templateName} />
                    </a-form-item>
                  </a-form>
                  <a-flex gap={12} justify="flex-end">
                    <a-button onClick={closeSavePopover}>取消</a-button>
                    <a-button type="primary" onClick={confirmSavePopover}>
                      确定
                    </a-button>
                  </a-flex>
                </>
              ),
            }}
          >
            <a-button type="primary" onClick={changeSavePopover}>
              保存模板
            </a-button>
          </a-popover>
          <a-popover
            v-model:open={selectTemplateVisible.value}
            trigger="click"
            v-slots={{
              content: () => (
                <>
                  <a-list
                    item-layout="horizontal"
                    data-source={templateList.value}
                    loading={listLoading.value}
                    v-slots={{
                      renderItem: ({ item }) => (
                        <>
                          <a-list-item>
                            <a-flex justify="space-between" align="center">
                              <span>{item.templateName}</span>
                              <a-button type="link" primary onClick={deleteTemplate(item.id)}>
                                删除
                              </a-button>
                            </a-flex>
                          </a-list-item>
                        </>
                      ),
                    }}
                  ></a-list>
                </>
              ),
            }}
          >
            <a-button type="primary" onClick={changeSelectPopover}>
              选择模板
            </a-button>
          </a-popover>
        </a-space>
      </>
    )
  },
})
